package com.itheima.tilas.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tilas.Utils.JwtUtil;
import com.itheima.tilas.Utils.ResultUtil;
import com.itheima.tilas.entity.Emp;
import com.itheima.tilas.mapper.EmpMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 过滤器测试类
 */
@Slf4j
public class TestFilter implements Filter {
    @Resource
    EmpMapper empMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("开始执行过滤");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        if (servletRequest.getRequestURI().contains("login")) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = servletRequest.getHeader("token");
        if (Objects.isNull(token)) {
            writeErrorMsg(servletResponse, "token为空");
            return;
        }
        try {
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            String username = jsonObject.getString("username");
            Emp emp = empMapper.selectEmpByUsername(username);
            if (Objects.isNull(emp) || !emp.getPassword().equals(jsonObject.getString("password"))) {
                writeErrorMsg(servletResponse, "用户名或密码错误");
                return;
            }
        } catch (Exception e) {
            writeErrorMsg(servletResponse, "token不合法");
            return;
        }
        chain.doFilter(servletRequest, servletResponse);
        log.info("过滤完成");
    }

    public static void writeErrorMsg(HttpServletResponse servletResponse, String msg) {
        //设置Json编码格式为Utf-8
        servletResponse.setContentType("application/json;charset=UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            PrintWriter writer = servletResponse.getWriter();
            ResultUtil fail = ResultUtil.fail(msg);
            writer.write(JSONObject.toJSONString(fail));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
